const csv = require('csvtojson');
const _ = require('lodash');
const Redis = require('ioredis');

const redis = new Redis({
  host: 'localhost',
  port: 6379,
});

async function start() {
  const j0 = await csv().fromFile('china-top-500-enterprises.csv');
  const top500 = _.map(j0, ({ no, name, revenue, profit }) => ({ no: +no, name, revenue: +revenue, profit: +profit }));

  for (const ep of top500) {
    await redis.call('JSON.SET', `china-top500-ep:${ep.no}`, '$', JSON.stringify(ep));
  }

  const result = await redis.call('JSON.GET', 'china-top500-ep:20', '$');
  console.log(JSON.stringify(result));

  {
    console.log('\n\n=> 按名称搜索');
    const result = await redis.call('FT.SEARCH', 'idx:china-top500-ep', "'@name:(中国铁建股份有限公司)'");
    console.log(JSON.stringify(result, null, '  '));
  }

  {
    console.log('\n\n=> 按范围搜索 profit');
    const result = await redis.call('FT.SEARCH', 'idx:china-top500-ep', "'@profit:[300000 +inf]'");
    console.log(JSON.stringify(result, null, '  '));
  }

  {
    console.log('\n\n=> 按范围搜索 revenue(sortable)');
    console.log(' > 第一批');
    let result = await redis.call(
      'FT.SEARCH',
      'idx:china-top500-ep',
      "'@revenue:[1000000 +inf]'",
      'SORTBY',
      'revenue',
      'LIMIT',
      '0', // 从第 0 个开始（包含）
      '5' // 往后查 5 个
    );
    console.log(JSON.stringify(result, null, '  '));

    console.log(' > 第二批');
    result = await redis.call(
      'FT.SEARCH',
      'idx:china-top500-ep',
      "'@revenue:[1000000 +inf]'",
      'SORTBY',
      'revenue',
      'DESC',
      'LIMIT',
      '5', // 从第 5 个开始（包含）
      '5' // 往后查 5 个
    );
    console.log(JSON.stringify(result, null, '  '));
  }

  {
    console.log('\n\n=> 按名称搜索前缀');
    const result = await redis.call('FT.SEARCH', 'idx:china-top500-ep', "'@name: 京东*'");
    console.log(JSON.stringify(result, null, '  '));
  }

  {
    console.log('\n\n=> 模糊');
    const result = await redis.call('FT.SEARCH', 'idx:china-top500-ep', "'@name: %京东%'");
    console.log(JSON.stringify(result, null, '  '));
  }

}

start()
  .then(() => {
    console.log('All DONE!');
    process.exit(0);
  })
  .catch((err) => {
    console.error('Error:', err);
    process.exit(1);
  });
